<?php


namespace app\agent\controller;

use app\admin\model\Admin;
use app\admin\model\Management;
use app\common\model\WorkLog;
use app\common\model\WorkOrder;
use EasyWeChat\Factory;
use app\common\library\Auth;
use fast\Http;
use think\Env;

class Manage extends \app\common\controller\Manage
{
    protected $noNeedLogin = ['config','oauth','login','testlogin'];
    protected $noNeedRight = ['*'];
    protected $app = '';
    protected $appconfig = '';
    protected $ModelMan;
    protected $modelLog;

    public function _initialize()
    {
        $this->appconfig = $this->config();
        $this->app = Factory::work($this->config());
        $this->auth = Auth::instance();
        $this->ModelMan = new Management();
        $this->model = new WorkOrder();
        $this->modelLog = new WorkLog();
        parent::_initialize();
    }

    public function testlogin()
    {
        $this->auth->IndexLogin('yangliu');
        return $this->redirect('index');
    }

    public function index()
    {
        if ($this->request->isAjax())
        {
            $this->searchFields = 'id,order_sn';
            list($where, $sort, $order,$offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order('status desc,id desc')
                ->count();
            $list = $this->model
                ->where($where)
                ->order('status asc,id desc')
                ->paginate($this->request->request('Pagesize',10),false,['query'=>request()->param()]);
            $status = [1=>'未回复',2=>'已回复',3=>'已完成'];
            foreach ($list as &$value)
            {
                $row = $this->modelLog->where('work_id','=',$value['id'])->order('id', 'desc')->find();
                $value['updatetime'] = date('Y-m-d',$value->updatetime);
                $value['title'] = $row ? $row['content'] :'';
                $value['status'] = $status[$value['status']];
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        $this->view->assign('search',$this->request->request('search',''));
        return $this->view->fetch();
    }

    public function info($id=null)
    {
        if(!$row = $this->model->get($id))
        {
            $this->error('ID错误');
        }
        $user = Admin::get(['userid'=>$row->create_userid]);
        $list = $this->modelLog->where('work_id','=',$id)->select();
        foreach ($list as &$value)
        {
            $admin = Admin::get(['userid'=>$value['userid']]);
            $value['userid_text'] = $admin['avatar'];
            $value['img'] = $value->img ? unserialize($value->img) : $value->img;
        }
        $this->view->assign('list',$list);
        $row['img'] = $row->img ? unserialize($row->img) : $row->img;
        $this->view->assign('row',$row);
        $this->view->assign('user',$user);

        return $this->view->fetch();
    }

    /**
     * 继续留言
     * @param null $id
     * @return string
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function edit($id = null)
    {
        if(!$row = $this->model->get($id))
        {
            $this->error('ID错误');
        }
        $this->view->assign('row',$row);
        return $this->view->fetch();
    }


    public function add()
    {
        if($this->request->isPost())
        {
            if(!$order = Management::get(['orderid'=>$this->request->request('order_sn')]))
            {
                $this->error('没有此订单号');
            }
           $result = $this->model->create([
                'order_sn'=>$order->orderid,
//                'yxj'=>$this->request->request('yxj'),
                'img'=>serialize(array_filter($this->request->request('img/a'))),
                'content'=>$this->request->request('content'),
                'create_userid'=>$this->auth->userid
            ]);
            if(!$result->id)
            {
                $this->error('数据添加错误');
            }
            $response = $this->message('有新的工单',$result->id);

            $this->success('工单添加成功！','index');

        }
        return $this->view->fetch();
    }

    public function OrderInfo($ids = null)
    {
        if(!$order = Management::get(['orderid'=>$ids]))
        {
            $this->error('没有此订单号');
        }
        $this->view->assign('order',$order);
        return $this->view->fetch();
    }

    public function orderSn()
    {
        if($this->request->isAjax()&& $this->request->request('order_sn'))
        {
            if($this->model->get(['order_sn'=>$this->request->request('order_sn'),'status'=>1]))
            {
                return ['status'=>0,'msg'=>'已经生成工单不可以再生成工单！'];
            }
            if($this->model->get(['order_sn'=>$this->request->request('order_sn'),'status'=>2]))
            {
                return ['status'=>0,'msg'=>'已经生成工单不可以再生成工单！'];
            }
            if($manRow = $this->ModelMan->get(['orderid'=>$this->request->request('order_sn')]))
            {
                return ['status'=>1,'msg'=>'订单号正确！'];
            }
            return ['status'=>0,'msg'=>'订单号不存在！'];
        }
        return ['status'=>0,'msg'=>'请求失败！'];
    }

    /**
     * 添加继续留言
     * @return array|\think\response\Json
     */
    public function workAddLog()
    {
        if(!$this->request->request('content'))
        {
            return json(['status'=>0,'msg'=>'请回复内容！']);
        }
        $res = $this->modelLog->save([
            'userid'=>$this->auth->userid,
            'content'=>$this->request->request('content'),
            'work_id'=>$this->request->request('work_id'),
            'img'=>serialize(array_filter($this->request->request('img/a')))
        ]);
        $this->model->save(['status'=>2],['id'=>$this->request->request('work_id')]);
        if(!$res)
        {
            $this->error();
        }
        $this->message('有新的回复',$this->request->request('work_id'));
        $this->success('添加成功！','/agent/manage/info/id/'.$this->request->request('work_id'));
    }

    public function close($id = null)
    {
        if(!$row = $this->model->get($id))
        {
            $this->error();
        }
        $row->status = 3;
        $row->save();
        $this->success('','index');
    }

    private function message($message,$id)
    {
        $token = $this->app->access_token->getToken();//获取企业微信token
        $url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={$token['access_token']}";
        $param = '{
                       "touser" : "'.Env::get('manage.reply').'",
                       "msgtype" : "text",
                       "agentid" : '.Env::get('manage.agent_id').',
                       "text" : {
                           "content" : " '.$message.'。<a href=\"http://oa.fc62.com/agent/manage/info/id/'.$id.'\">查看</a>，请尽快处理。"
                       }
                    }';
        $response = Http::post($url,$param);
        return $response;
    }

    private  function config()
    {
        $config = [
            'agent_id' => Env::get('manage.agent_id'),
            'corp_id' => Env::get('user.corp_id'),
            'secret'   => Env::get('manage.secret'),
            'response_type' => Env::get('manage.response_type'),
            'log' => [
                'level' => Env::get('manage.level'),
                'file' => __DIR__.Env::get('manage.file'),
            ],
            'oauth'=> [
                'scopes'=> Env::get('manage.scopes'),
                'callback' => Env::get('manage.callback')
            ],
            //收信息人员
            'message'=>[
                'reply'=>Env::get('manage.reply'),
            ]
        ];
        return $config;
    }

    public function oauth()
    {
        $token = $this->app->access_token->getToken();//获取企业微信token
        $code = $this->request->request('code');
        $url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={$token['access_token']}&code={$code}";
        $user = \fast\Http::get($url);
        if(!empty($user)) $user = json_decode($user,true);
        if($user['errcode'] == 0){
            if(isset($user['UserId'])){
                if(!$this->auth->IndexLogin($user['UserId'])){
                    $this->error(__('您的账户不存在，请联系管理员'));
                }else{
                    return redirect('/agent/manage/index');
                }
            }
        }else{
            return redirect($this->request->domain().'/agent/manage/index');
        }
    }

    public function login()
    {
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->appconfig['corp_id']."&redirect_uri=".$this->appconfig['oauth']['callback']."&response_type=code&scope=".$this->appconfig['oauth']['scopes']."&agentid=".$this->appconfig['agent_id']."&state=1#wechat_redirect";
        return redirect($url);
    }

}